const _ = require("lodash");

/**
    * Created by Syaoran on 2021/12/29.
    * 重置对象所有的属性值
    * @param { Object } obj: 要处理的对象
    * @param { Array } list: 要忽略的键名
*/
export function resetObject (obj, list) {
    if (!_.isObject(obj)) return;
    for (let key in obj) {
        const ignoreIndex = _.findIndex(list, item => {
            return item === key;
        });
        if (ignoreIndex === -1) {
            if (_.isArray(obj[key])) obj[key] = [];
            else if (_.isObject(obj[key])) obj[key] = resetObject(obj[key]);
            else obj[key] = "";
        }
    }
    return obj;
}

/* 将数组按某个属性名递归为一维数组 */
export function flattenDeepBy (array = [], key = "children") {
    const result = [];
    const flatten = (arr) => {
        arr.forEach(i => {
            result.push(i);
            if (i[key] && _.isArray(i[key]) && i[key].length) flatten(i[key]);
        });
    };
    flatten(array);
    return result;
}

/**
 * Created by Syaoran on 2021/12/23.
 * 将对象中的下划线命名替换为驼峰式命名
 * @param {String} obj: 要转换的对象
 */
export function jsonToHump(obj) {
    if (_.isArray(obj)) {
        obj.forEach(i => {
            jsonToHump(i);
        });
    }
    else if (_.isObject(obj)) {
        _.forIn(obj, (value, key) => {
            const newKey = _.camelCase(key);
            if (key !== newKey) {
                obj[newKey] = value;
                delete obj[key];
            }
            jsonToHump(obj[newKey]);
        });
    }
}

/**
 * Created by Syaoran on 2022/7/27.
 * 将对象、数组中的undefined转为空string
 * @param {String} obj: 要转换的对象
 */
export function formatObjectUndefined (obj) {
    const object = _.forIn(obj, (value, key) => {
        console.log(key + ":", value);
        if (_.isArray(value)) value = formatArrayUndefined(value);
        else if (_.isObject(value)) value = formatObjectUndefined(value);
        else if (value === undefined) value = "";
    });
    return object;
}
export function formatArrayUndefined (arr) {
    const array = _.cloneDeep(arr);
    array.forEach(item => {
        if (_.isArray(item)) item = formatArrayUndefined(item);
        else if (_.isObject(item)) item = formatObjectUndefined(item);
        else if (item === undefined) item = "";
    });
    return array;
}